//
//  TCRedBookDealVC.m
//  PearRich
//
//  Created by apple on 2020/12/25.
//  Copyright © 2020 谢黎鹏. All rights reserved.
//

#import "TCRedBookDealVC.h"
#import "QRCodeInputTV.h"
#import <TFHpple/TFHpple.h>
#import <WebKit/WebKit.h>
#import "PRRedBookColCell.h"
@interface TCRedBookDealVC ()<WKNavigationDelegate,WKUIDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
@property(nonatomic,retain)UIView * shelterView;
@property (nonatomic, strong) WKWebView *web;
@property(nonatomic,retain)UICollectionView * myCol;
@property(nonatomic,retain)NSMutableArray * dataArr, * choseArr;
@end

@implementation TCRedBookDealVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArr = [NSMutableArray new];
    self.choseArr = [NSMutableArray new];
    [self.view addSubview:self.myCol];
    self.rightBtnName = @"保存";
    self.rightBtnNameColor = TextColor;
    self.rightBtnFontSize = 16;
    [self getData];
}
- (void)rightBtnClick{
    if (self.choseArr.count == 0) {
        XHQHUDErrorText(@"至少选择一张图片");
        return;
    }
    __block int count = 0;
    for (NSString * url in self.choseArr) {
        [[SDWebImageManager sharedManager]loadImageWithURL:URL(url) options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            count ++;
            [Mytools saveImageToLocal:image];
            if (count == self.choseArr.count) {
                XHQHUDSuccessText(@"保存完成");
            }
        }];
    }
}
-(void)getData{
    UIPasteboard * board = [UIPasteboard generalPasteboard];
    if (board.string.length == 0) {
        [self.view addSubview:self.shelterView];
        QRCodeInputTV * vc = [[QRCodeInputTV alloc]initWithFrame:Frame(15, IPHONE_HEIGHT/2.f-125, IPHONE_WIDTH-30, 250)];
        [self.shelterView addSubview:vc];
        __weak typeof(vc)weakV = vc;
        vc.aniBlock = ^(NSString * _Nonnull str) {
            [weakV removeFromSuperview];
            [self.shelterView removeFromSuperview];
            self.shelterView = nil;
            [self getContentWithUrl:str];
        };
        vc.transform = CGAffineTransformMakeScale(0.01, 0.01);
        [UIView animateWithDuration:0.35 animations:^{
            self.shelterView.alpha = 1;
            vc.transform = CGAffineTransformMakeScale(1.0, 1.0);
        }];
    }else{
        [self getContentWithUrl:board.string];
    }
}
-(void)getContentWithUrl:(NSString*)url{
    NSArray * urlList = [Mytools filterUrlWithString:url];
    if (urlList.count == 0 ) {
        XHQHUDErrorText(@"解析失败");
    }else{
        NSString * finalUrl = urlList.firstObject;
        WKWebViewConfiguration *config = [WKWebViewConfiguration new];
        self.web = [[WKWebView alloc]initWithFrame:Frame(0, 100, 50, 50) configuration:config];
        self.web.backgroundColor = UIColorWhite;
        self.web.navigationDelegate = self;
        [self.view addSubview:self.web];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:finalUrl]];
        [_web loadRequest:request];
    }
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    // 获取完整url并进行UTF-8转码
    NSString *strRequest = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];
    if ([strRequest containsString:@"discovery/item"]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        [self.web removeFromSuperview];
        self.web = nil;
        // 拦截点击链接
        NSString *htmlString = [NSString stringWithContentsOfURL:[NSURL URLWithString:strRequest] encoding:NSUTF8StringEncoding error:nil];
        NSString * prex = @"//ci.xiaohongshu.com/\\S+format/jpg";
        NSError * error = nil;
        NSRegularExpression*regex = [NSRegularExpression regularExpressionWithPattern:prex options:NSRegularExpressionCaseInsensitive error:&error];
        NSArray*arr = [regex matchesInString:htmlString options:NSMatchingReportCompletion range:NSMakeRange(0, htmlString.length)];
        for(NSTextCheckingResult*match in arr){
            NSString* substringForMatch = [htmlString substringWithRange:match.range];
            if ([substringForMatch containsString:@"?imageView"]) {
                PRRedBookColModel * mo = [PRRedBookColModel new];
                mo.url = [NSString stringWithFormat:@"https:%@",substringForMatch];
                mo.isChose = NO;
                [self.dataArr addObject:mo];
            }
        }
        [self.myCol reloadData];
    }else {
        // 允许跳转
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}
//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    VLog(@"加载完成");
}
//加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    VLog(@"加载失败");
}
- (UIView *)shelterView{
    if (_shelterView == nil) {
        _shelterView = [[UIView alloc]initWithFrame:Frame(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)];
        _shelterView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7];
        _shelterView.alpha = 0;
    }
    return _shelterView;
}
#pragma mark 代理
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArr.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PRRedBookColCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PRRedBookColCell" forIndexPath:indexPath];
    if (indexPath.row < self.dataArr.count) {
        cell.model = self.dataArr[indexPath.row];
    }
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row < self.dataArr.count) {
        PRRedBookColModel * mo = self.dataArr[indexPath.row];
        mo.isChose = !mo.isChose;
        if (mo.isChose) {
            if (![self.choseArr containsObject:mo.url]) {
                [self.choseArr addObject:mo.url];
            }
        }else{
            if ([self.choseArr containsObject:mo.url]) {
                [self.choseArr removeObject:mo.url];
            }
        }
        [collectionView reloadItemsAtIndexPaths:@[indexPath]];
    }
}
- (UICollectionView *)myCol{
    if (!_myCol) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        CGFloat margin = 10;
        CGFloat between = 5;
        CGFloat itemWidth = floor((SCREEN_WIDTH - margin * 2 - between * 3)/4.f);
        layout.itemSize = CGSizeMake(itemWidth, itemWidth);
        layout.minimumInteritemSpacing = between;
        layout.minimumLineSpacing = between;
        // 设置每个分区的 上左下右 的内边距
        layout.sectionInset = UIEdgeInsetsMake(margin,margin ,margin, margin);
        _myCol = [[UICollectionView alloc]initWithFrame:Frame(0, kTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT - kTopHeight -KTabbarSafeBottomMargin) collectionViewLayout:layout];
        _myCol.delegate = self;
        _myCol.dataSource = self;
        _myCol.backgroundColor = [UIColor normalColor:UIColorWhite darkColor:UIColorBlack];
        [_myCol registerClass:[PRRedBookColCell class] forCellWithReuseIdentifier:@"PRRedBookColCell"];
    }
    return _myCol;
}
@end
